package com.nl.controller.web.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nl.controller.common.annotation.SystemServiceLog;
import com.nl.controller.common.exception.SmsException;
import com.nl.controller.common.interceptor.SysContext;
import com.nl.controller.common.service.CommonService;
import com.nl.controller.common.util.AES;
import com.nl.controller.web.bean.SmsArtificialRecord;
import com.nl.controller.web.bean.SmsUsers;
import com.nl.controller.web.bean.UserUploadArtificial;
import com.nl.controller.web.global.GlobalConst;
import com.nl.controller.web.mapper.SmsArtificialRecordMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class SmsArtificialRecordService {
    @Autowired
    private SmsArtificialRecordMapper smsArtificialRecordMapper;

    @Autowired
    private CommonService commonService;

    @SystemServiceLog(description = "初始化手工发送的批次号", value = false)
    public String initBatchNumber() {
        String batchNumber = "";
        try {
            batchNumber = smsArtificialRecordMapper.findBatchNumber();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("初始化手工发送的批次号");
            throw new SmsException("初始化手工发送的批次号异常");
        }
        return batchNumber;
    }

    @SystemServiceLog(description = "该项目已有查询", value = false)
    public int findLink(String mgrId,String userId){
    	int result=0;
    	try{   		
    		result=smsArtificialRecordMapper.findLink(mgrId,userId);
    	}catch (Exception e) {
            e.printStackTrace();
            throw new SmsException("项目今日已有查询异常");
        }
    	return result;
    }
    
    @SystemServiceLog(description = "文件上传记录添加", value = false)
    public int addUploadRecord(String mgrId, String cityId,String countyId ,String sendTime, String remark, String batchNumber, int uploadNumber,String joinFrequencyRoom,String overExpire
    		) {
    	HttpSession session = SysContext.getRequest().getSession();
    	SmsUsers user = (SmsUsers) session.getAttribute("user");
        int result = 0;
        
        //发送时间进行处理
        if (!"".equals(sendTime) && sendTime != null) {
            StringBuffer sbf = new StringBuffer();
            sendTime = sbf.append(sendTime.substring(0, 15)).append("0:00").toString();
        }
        
        
        
        SmsArtificialRecord smsArtificialRecord = new SmsArtificialRecord();
        smsArtificialRecord.setBatchNumber(batchNumber);
        smsArtificialRecord.setCityId(cityId);
        if (!"".equals(countyId) && null!=countyId) {
        	smsArtificialRecord.setCountyId(countyId);
        }else{
        	String countyid=smsArtificialRecordMapper.findCountyId(mgrId);
            	smsArtificialRecord.setCountyId(countyid); 
        }
        
        smsArtificialRecord.setId(mgrId);
        smsArtificialRecord.setSendTime(sendTime);
        smsArtificialRecord.setJoinFrequencyRoom(joinFrequencyRoom);
        smsArtificialRecord.setOverExpire(overExpire);
        UserUploadArtificial userUploadArtificial= new UserUploadArtificial();
        userUploadArtificial.setMgrId(mgrId);
        userUploadArtificial.setUserId(user.getUserId());
        userUploadArtificial.setUserName(user.getUserName());
        userUploadArtificial.setMsisdn(user.getMsisdn());
        userUploadArtificial.setDuty(user.getDuty());
        userUploadArtificial.setUploadNumber(uploadNumber);
        try {
            result = smsArtificialRecordMapper.addUploadRecord(smsArtificialRecord);
            smsArtificialRecordMapper.addLinkRecord(userUploadArtificial);
        } catch (Exception e) {
            e.printStackTrace();
            throw new SmsException("手工发送记录添加异常");
        }
        return result;
    }


    @SystemServiceLog(description = "根据条件查询基站信息", value = false)
    public PageInfo<SmsArtificialRecord> findUploadRecord(int page, int limit, String cityId, String countyId , String mgrId, String sendTime, String batchNumber, String mgrName) {
        Map<String, Object> map = new HashMap<>();
        map.put("cityId", cityId);
        map.put("countyId", countyId);
        map.put("mgrId", mgrId);
        map.put("sendTime", sendTime);
        map.put("batchNumber", batchNumber);
        map.put("mgrName", mgrName);
        PageHelper.startPage(page, limit);
        List<SmsArtificialRecord> list = new ArrayList<>();
        try {
            PageHelper.startPage(page, limit);
            list = smsArtificialRecordMapper.findUploadRecord(map);
            for (SmsArtificialRecord smsArtificialRecord : list) {
				if ((!"25".equals(smsArtificialRecord.getCityId())) && (null != smsArtificialRecord.getCountyId())
						&& (!"".equals(smsArtificialRecord.getCountyId()))) {
					String province =  smsArtificialRecord.getCityName() + "市" + "/" + smsArtificialRecord.getCountyName();
					smsArtificialRecord.setProvince(province);
				} else if ((!"25".equals(smsArtificialRecord.getCityId())) && (null == smsArtificialRecord.getCountyId())) {
					String province =  smsArtificialRecord.getCityName() + "市";
					smsArtificialRecord.setProvince(province);
				} else {
					String province = "江苏省";
					smsArtificialRecord.setProvince(province);
				}
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询手工发送记录");
            throw new SmsException("查询手工发送记录出现异常");
        }
        PageInfo<SmsArtificialRecord> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }


    @SystemServiceLog(description = "根据项目编码查询批次号", value = false)
    public List<SmsArtificialRecord> findBatchNumberList(String mgrId) {
        List<SmsArtificialRecord> list = new ArrayList<>();
        try {

            list = smsArtificialRecordMapper.findBatchNumberList(mgrId);
            list = decrypt(list);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取批次号列表失败");
            throw new SmsException("获取批次号列表失败");
        }
        return list;
    }


    @SystemServiceLog(description = "查看导入和发送结果", value = false)
    public List<String> getState(String batchNumber) {
        List<String> list = new ArrayList<>();
        try {
            list.add(smsArtificialRecordMapper.findStateSuccess(batchNumber));
            list.add(smsArtificialRecordMapper.findStateFail(batchNumber));
            list.add(smsArtificialRecordMapper.findSendStateSuccess(batchNumber));
            list.add(smsArtificialRecordMapper.findSendStateFail(batchNumber));

        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询手工发送结果失败");
            throw new SmsException("查询手工发送结果失败");
        }
        return list;
    }

    public PageInfo<SmsArtificialRecord> findSendDeatil(int page, int limit, String batchNumber) {
        PageHelper.startPage(page, limit);
        List<SmsArtificialRecord> list = null;
        try {
            PageHelper.startPage(page, limit);
            list = smsArtificialRecordMapper.findSendDetail(batchNumber);
            list = decrypt(list);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询手工发送明细");
            throw new SmsException("查询手工发送明细出现异常");
        }
        PageInfo<SmsArtificialRecord> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }
    private List<SmsArtificialRecord> decrypt(List<SmsArtificialRecord> list){
        if (list != null) {
            for (SmsArtificialRecord smsArtificialRecord : list) {
                String msisdn = smsArtificialRecord.getMsisdn();
                log.info("解密前："+msisdn);
                if (msisdn!=null && !"".equals(msisdn)) {
                    String decrypt;
                    try {
                        decrypt = AES.decrypt(msisdn, GlobalConst.SKEY);
                        log.info("解密后："+decrypt);
                        smsArtificialRecord.setMsisdn(decrypt);
                    } catch (Exception e) {
                        log.info("解密失败");
                        e.printStackTrace();
                    } 
                }  
            }
        }  
        return list;
    }
}
